package com.pig4cloud.pig.djjk.service;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.Response;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.pig4cloud.pig.djjk.config.HikProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static com.hikvision.artemis.sdk.util.HttpUtil.wrapClient;

@Service
@Slf4j
public class HikService {
    @Autowired
    HikProperties hikProperties;

    public JSONObject cameraSearch(int pageNo,int pageSize){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNo",pageNo);
        jsonObject.put("pageSize",pageSize);
        jsonObject.put("treeCode","0");
		String artemisResponseBody = getArtemisResponseBody("/api/resource/v1/cameras", jsonObject.toString());
		log.info("获取摄像头信息,{}",artemisResponseBody);
		if(StrUtil.isNotBlank(artemisResponseBody)){
			JSONObject respJson = JSON.parseObject(artemisResponseBody);
			if(respJson.getInteger("code") == 0){
				JSONObject dataJson = respJson.getJSONObject("data");
				if(dataJson!= null){
					return dataJson;
				}
			}
		}
		log.error("获取摄像头信息失败,{}",artemisResponseBody);
		return null;
	}

	public JSONObject regionsSearch(int pageNo,int pageSize){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("pageNo",pageNo);
		jsonObject.put("pageSize",pageSize);
		jsonObject.put("treeCode","0");
		String artemisResponseBody = getArtemisResponseBody("/api/resource/v1/regions", jsonObject.toString());

//		String artemisResponseBody = ResourceUtil.readUtf8Str("region.json");
		log.info("获取区域信息,{}",artemisResponseBody);
		if(StrUtil.isNotBlank(artemisResponseBody)){
			JSONObject respJson = JSON.parseObject(artemisResponseBody);
			if(respJson.getInteger("code") == 0){
				JSONObject dataJson = respJson.getJSONObject("data");
				if(dataJson != null){
					return dataJson;
				}
			}
		}
		log.error("获取区域信息失败,{}",artemisResponseBody);
		return null;
	}

	public String previewURLs(String cameraIndexCode,String protocol){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("cameraIndexCode",cameraIndexCode);
		jsonObject.put("streamType",0);
//		jsonObject.put("protocol","rtmp");
		jsonObject.put("protocol",protocol);
//		jsonObject.put("protocol","hls");
		jsonObject.put("transmode",0);
		jsonObject.put("expand","transcode=0");
		String artemisResponseBody = getArtemisResponseBody("/api/video/v1/cameras/previewURLs", jsonObject.toString());
		log.info("获取预览地址,{}",artemisResponseBody);
		if(StrUtil.isNotBlank(artemisResponseBody)){
			JSONObject respJson = JSON.parseObject(artemisResponseBody);
			if(respJson.getInteger("code") == 0){
				JSONObject dataJson = respJson.getJSONObject("data");
				if(dataJson!= null){
					return dataJson.getString("url");
				}
			}
		}
		log.error("获取预览地址失败,{}",artemisResponseBody);
		return "";
	}

    @SneakyThrows
    public String getArtemisResponseBody(String url,String requestJson){
        ArtemisConfig config = getArtemisConfig();
        final String getCamsApi = hikProperties.getArtemisPath() + url;
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        return ArtemisHttpUtil.doPostStringArtemis(config,path, requestJson, null, null, "application/json");
    }

    @NotNull
    private ArtemisConfig getArtemisConfig() {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(hikProperties.getHost()); // 代理API网关nginx服务器ip端口
        config.setAppKey(hikProperties.getAk());  // 秘钥appkey
        config.setAppSecret(hikProperties.getSk());// 秘钥appSecret
        return config;
    }


    /**
     * 调用POST接口，返回图片
     * 接口实际url：https://ip:port/artemis/api/visitor/v1/record/pictures
     * @return
     */
    public String callPostImgs() throws Exception {
        ArtemisConfig config = getArtemisConfig();
        final String getSecurityApi = hikProperties.getArtemisPath() + "/api/visitor/v1/record/pictures"; // 接口路径
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getSecurityApi);
            }
        };
        Map<String, String> head = new HashMap<String, String>(2) {  //get请求的head参数
            {
                put("headpost", "sky-test");
            }
        };
        Map<String, String> query = new HashMap<String, String>(2) {  //get请求的head参数
            {
                put("domainId", "0");
            }
        };
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("svrIndexCode", "9ff58bc2-65a5-464b-b28c-daea67ba9569");
        jsonBody.put("picUri", "/pic?9dda12i40-e*5b84626c4105m5ep=t=i3p*i=d1s*i=d3b*i1d3b*855925cea-96008b--2718943z855s=5i76=");
        String body = jsonBody.toJSONString();
        //参数根据接口实际情况设置
        //参数根据接口实际情况设置
        //【注】：该方法从artemis-http-client v1.1.12版本后，返回值修改为Response，此前为HttpResponse;升级时注意兼容性问题
        Response result = ArtemisHttpUtil.doPostStringImgArtemis(config, path, body, null, null, "application/json", null);

        try {

            if (302==result.getStatusCode()) {
                /*
                获取图片数据保存到本地
                注：1.对于有时效的图片，必须尽快保存到本地
                   2.若无时效，则可以直接保存location，后续自行访问获取
                 */
                String location=  result.getHeader("Location");
                HttpGet httpget = new HttpGet(location);
                HttpClient httpClient = wrapClient(httpget.getURI().getScheme()+"://"+httpget.getURI().getHost());
                HttpResponse execute = httpClient.execute(httpget);
                HttpEntity entity = execute.getEntity();
                InputStream in = entity.getContent();
                //TODO 可以返回保存后的路径
            }else{
                System.out.println("下载出错:"+result.getBody());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return getSecurityApi;
    }

}
